// pages/home/home.js
import util from '../../utils/CoordinateUtil'
import {getCarTravel} from '../../utils/api.js';
const RSA = require('../../utils/wx_rsa')
const app = getApp();
const iconPath = "/static/location.png";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    markers: [], // 标记点集合
    carPoint: {}, // 车辆点位
    polyline: [], // 坐标点集合
    satellite: false, // 是否开启卫星图,
    isCarMoving: false, // 小车是否在移动
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // wx.getLocation({
    //   success: (res) => {
    //     this.mapCtx = wx.createMapContext('map');
    //     this.setData({
    //       latitude: res.latitude,
    //       longitude: res.longitude
    //     })
    //   }
    // })
  },
  beginRequest() {
    getCarTravel({
      plateNumber: '13816638969',
      startTime: '2022-08-25 08:11:52',
      endTime: '2022-12-26 08:11:52'
    }, res => {
      console.log("GPS数据请求成功", res.result[0])
      let points = res.result.map(v => util.transformFromWGSToGCJ(v.Lat, v.Lng)).map((v, i) => {
        let callout = {};
        if(i === 0){
          callout = {
            content: '起点',
            anchorX: -13,
            bgColor: "#FFFFFF"
          }
        }else if(i === res.result.length - 1){
          callout = {
            content: '终点',
            anchorX: -13,
            bgColor: "#FFFFFF"
          }
        }
        return {
          latitude: v.latitude, 
          longitude: v.longitude,
          id: i + 1,
          width: 40,
          height: 40,
          label: callout
        }
      });
      let markers = [points[0], points[points.length - 1]];
      let carPoint = {
        ...points[0],
        id: points.length + 1,
        iconPath: "/static/car1.png",
        color: "#ff00ff",
        bgColor: "#FFFFFF",
        label: {
          anchorX: -20,
          bgColor: "#FFFFFF"
        }
      };
      this.setData({
        polyline: [{
          points: points,
          arrowLine: true,
          color: "#53B771",
          width: 7,
        }],
        markers: [...markers, carPoint],
        latitude: carPoint.latitude,
        longitude: carPoint.longitude,
        carPoint: carPoint
      })
      setTimeout(() => this.beginTrack(), 1000);
    })
  },

  beginEncrypt() {
    var privateKey_pkcs8 = '-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BA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BK4dYYdLKadrc/vEyecsCRl8MRSTgbFEEDMSce/MGv3CceO +57up3/vV1k9rSMUDm5rabBTRiIF3h4Xoc1HflmGj1MgzrQUY24d3puIFtgaCTzc oyTM/Rm6XD2gGlIrYcv4u3T15yETDZYDf7FgCB5T/393XZPQ4Na/aT0QRQKBgQCO 1kT2/7Hov0P3qnyGsGZZB5hXfff+A+eveUuJqtjoBVReFfwXQu8UU86l+BTAM1gZ wF5JlvERktMw6zKfhtaYyEm1qF0kCCCqeqeGLHciD/2/I36wKeEm9hsdjxyxjm/P 4jIrFQV4aFJd/glhCRQgxN7kJofY1EDNaa7yglh9cQKBgG0K8LiXG+zxDT2SzJWe N65FmYepYMrHOqx2Vsz8o58/TGkGZnGNyqbhOzeYaboC6Zl4z6Eiy0FZgfLH2JX1 kc0C/Ij0lu3mQfk/cfX634zwt8IUlW7Hy9AkedaRAnndmwx188KEpSBGrghDEtV8 i8jTQpsLOLJ35b17oa6Q7tjb -----END PRIVATE KEY-----'
    var publicKey_pkcs8 = '-----BEGIN RSA PUBLIC KEY-----MIIBCgKCAQEAzlkarAkHk/Z0YvjGYncwlkN6uj1zqnX8kOjzWjVD+a8PZ14F+/i2fd4H/LaN2sST5lTtrfoMISskijIn/NWj1D0ZWpiod3Kmlzu4aMdhZpZx2EDoP99Hy4LxAw7Q7fFBuGzPfEgvwl8jvwOwIr5o3H3ICVEamesFd+bfvxrIxVQ4R+2HclfLJrltCXTykNeLag44D6fAluDymm275vFXJBzKxnhBeJbSHyvUIknQZrxL1LUPCb7Dgkmm+svx72FFiKDMnXWU9LcFwE29RW6IxIlabnqOu7oYNu50A0gI6pO+haANupr3NWO3lGjU6hnInZ8yX2gfSyPr7zn4RXX12wIDAQAB-----END RSA PUBLIC KEY-----'


    // 加签
    var sign_rsa = new RSA.RSAKey(); 
    sign_rsa = RSA.KEYUTIL.getKey(privateKey_pkcs8); 
    console.log('签名RSA:')
    console.log(sign_rsa)
    var hashAlg = 'sha1';
    var hSig = sign_rsa.signString("signData", hashAlg); 
    hSig = RSA.hex2b64(hSig); // hex 转 b64
    console.log("签名结果：" + hSig)
    // // 验签
    // var verify_rsa = new RSA.RSAKey();
    // verify_rsa = RSA.KEYUTIL.getKey(publicKey_pkcs8);
    // console.log('验签RSA:')
    // console.log(verify_rsa)
    // hSig = RSA.b64tohex(hSig)
    // var ver = verify_rsa.verifyString("signData", hSig) 
    // console.log('验签结果：' + ver)

    // // 加密 【加密字段长度不大于117】
    // var encrypt_rsa = new RSA.RSAKey();
    // encrypt_rsa = RSA.KEYUTIL.getKey(publicKey_pkcs8);
    // console.log('加密RSA:')
    // console.log(encrypt_rsa)
    // var encStr = encrypt_rsa.encrypt('123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567')
    // encStr = RSA.hex2b64(encStr);
    // console.log("加密结果：" + encStr)

    // // 解密
    // var decrypt_rsa = new RSA.RSAKey();
    // decrypt_rsa = RSA.KEYUTIL.getKey(privateKey_pkcs8);
    // console.log('解密RSA:')
    // console.log(decrypt_rsa)
    // encStr = RSA.b64tohex(encStr)
    // var decStr = decrypt_rsa.decrypt(encStr)
    // console.log("解密结果：" + decStr)
  },
  beginNavigation() {
    let lastPoint = this.data.markers[this.data.markers.length - 1];
    let p = util.transformFromGCJToWGS(lastPoint.latitude, lastPoint.longitude);
    this.mapCtx.openMapApp({
      latitude: p.latitude,
      longitude: p.longitude,
      destination: "目的地"
    })
  },
  beginTrack() {
    if (this.data.isCarMoving) {
      return
    }
    if(typeof this.data.polyline === 'undefined'){
      return ;
    }
    this.data.isCarMoving = true;
    // 缩放视野展示所有点位
    this.mapCtx.includePoints({
      points: this.data.markers,
      padding: [30, 30, 30, 30]
    });
    // 把小车移动到起点
    this.mapCtx.translateMarker({
      markerId: this.data.carPoint.id,
      destination: this.data.polyline[0].points[0],
      autoRotate: false,
      rotate: 0,
      duration: 200
    })
    // 将小车递归遍历所有点位
    this.translateMarker(this.data.polyline[0].points, 0);
  },
  // 平移marker，带动画
  translateMarker: function (points, i) {
    let that = this;
    let markerId = this.data.carPoint.id;
    let destination = points[i + 1];
    let car = that.data.carPoint;
    let distance = util.getDistance(points[i], points[i + 1]);
    let duration = distance * 0.5; // 根据距离计算平移的速度，看起来保持匀速
    // 目的地和车是同一个 不执行动画
    if (i !== 0 && destination.latitude === car.latitude && destination.longitude === car.longitude) {
      this.data.isCarMoving = false;
      return
    }
    this.mapCtx.translateMarker({
      markerId: markerId,
      destination: destination,
      autoRotate: false,
      rotate: 0,
      duration: duration,
      success: (res) => {
        if(i < points.length - 2){
          that.translateMarker(points, ++i);
        }else{
          this.data.isCarMoving = false;
        }
      },
      fail(err) {
        console.log('fail', err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})